package com.erp.web.controller.framework;


import com.erp.framework.annotation.Log;
import com.erp.framework.constant.ConfigConstants;
import com.erp.framework.constant.Constants;
import com.erp.framework.core.controller.BaseController;
import com.erp.framework.core.domain.AjaxResult;
import com.erp.framework.core.page.TableDataInfo;
import com.erp.framework.core.text.Convert;
import com.erp.framework.domain.SysUser;
import com.erp.framework.enums.BusinessType;
import com.erp.framework.service.ISysRoleService;
import com.erp.framework.service.ISysUserService;
import com.erp.framework.shiro.service.SysLoginService;
import com.erp.framework.util.ShiroUtils;
import com.erp.framework.util.StringUtils;
import com.erp.framework.util.poi.ExcelUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 用户信息
 *
 * @author erp
 */
@Controller
@RequestMapping("/framework/user")
public class SysUserController extends BaseController {

    private final String prefix = "framework/user";

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private SysLoginService loginService;

    @RequiresPermissions("framework:user:view")
    @GetMapping()
    public String user() {
        return prefix + "/user";
    }

    @RequiresPermissions("framework:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.list(user);
        list.forEach(u -> {
            u.setPassword(null);
            u.setSalt(null);
        });
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("framework:user:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysUser user) {
        List<SysUser> list = userService.list(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("framework:user:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        return userService.importUser(userList, updateSupport);
    }

    @RequiresPermissions("framework:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        mmap.put("roles", roleService.selectRoleAll());
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("framework:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysUser user) {
        if (userService.checkUserNameUnique(user.getUserName())) {
            return error("新增用户[" + user.getUserName() + "]失败，用户名已存在");
        }
        if (StringUtils.isNotBlank(user.getEmail())
                && userService.checkEmailUnique(user.getEmail())) {
            return error("新增用户[" + user.getUserName() + "]失败，邮箱账号已存在");
        }
        if (StringUtils.isNotBlank(user.getPhoneNumber())
                && userService.checkPhoneUnique(user.getPhoneNumber())) {
            return error("新增用户[" + user.getUserName() + "]失败，手机号码已存在");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(loginService.encryptPassword(user.getUserName(), user.getPassword(), user.getSalt()));
        return toAjax(userService.insert(user));
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(id));
        mmap.put("roles", roleService.selectRolesByUserId(id));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("framework:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysUser user) {
        userService.checkUserAllowed(user);
        if (StringUtils.isNotBlank(user.getEmail())
                && userService.checkEmailUnique(user.getEmail())) {
            return error("修改用户[" + user.getUserName() + "]失败，邮箱账号已存在");
        }
        if (StringUtils.isNotBlank(user.getPhoneNumber())
                && userService.checkPhoneUnique(user.getPhoneNumber())) {
            return error("修改用户[" + user.getUserName() + "]失败，手机号码已存在");
        }
        return toAjax(userService.update(user));
    }


    @RequiresPermissions("framework:user:resetPwd")
    @GetMapping("/resetPwd/{id}")
    public String resetPwd(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(id));
        return prefix + "/resetPwd";
    }

    @RequiresPermissions("framework:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(SysUser user) {
        userService.checkUserAllowed(user);
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(loginService.encryptPassword(user.getUserName(), user.getPassword(), user.getSalt()));
        if (userService.resetUserPwd(user) > 0) {
            if (ShiroUtils.getId().equals(user.getId())) {
                ShiroUtils.setSysUser(userService.selectUserById(user.getId()));
            }
            return success();
        }
        return error();
    }

    /**
     * 进入授权角色页
     */
    @GetMapping("/authRole/{id}")
    public String authRole(@PathVariable("id") String id, ModelMap mmap) {
        // 获取用户所属的角色列表
        mmap.put("user", userService.selectUserById(id));
        mmap.put("roles", roleService.selectRolesByUserId(id));
        return prefix + "/authRole";
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("framework:user:add")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PostMapping("/authRole/insertAuthRole")
    @ResponseBody
    public AjaxResult insertAuthRole(String userId, String[] roleIds) {
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    @RequiresPermissions("framework:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        String[] idArray = Convert.toStrArray(ids);
        for (String id : idArray) {
            SysUser temp = new SysUser();
            temp.setId(id);
            disable(temp);
        }
        return success();
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public boolean checkLoginNameUnique(SysUser user) {
        return StringUtils.isNotBlank(user.getUserName()) && userService.checkUserNameUnique(user.getUserName());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public boolean checkPhoneUnique(SysUser user) {
        return StringUtils.isNotBlank(user.getPhoneNumber()) && userService.checkPhoneUnique(user.getPhoneNumber());
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public boolean checkEmailUnique(SysUser user) {
        return StringUtils.isNotBlank(user.getEmail()) && userService.checkEmailUnique(user.getEmail());
    }

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("framework:user:edit")
    @PostMapping("/disable")
    @ResponseBody
    public AjaxResult disable(SysUser user) {
        userService.checkUserAllowed(user);
        user.setStatus(ConfigConstants.DISABLE);
        return toAjax(userService.update(user));
    }

    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("framework:user:edit")
    @PostMapping("/enable")
    @ResponseBody
    public AjaxResult enable(SysUser user) {
        userService.checkUserAllowed(user);
        user.setStatus(ConfigConstants.ENABLE);
        return toAjax(userService.update(user));
    }

}